<template>
  <!-- 查询条件 -->
  <div class="pb-5 pt-5">
    <NSpace>
      <!-- 选择器 -->
      <NSelect
        v-model:value="queryInfo.logType"
        :options="types"
        :consistent-menu-width="false"
      ></NSelect>

      <!-- 输入框 -->
      <NInput v-model:value="queryInfo.logInfo" placeholder="日志模糊查询"></NInput>
      <NButton type="primary" @click="requery">确定</NButton>
      <NButton type="error" @click="reset">重置</NButton>
    </NSpace>
  </div>

  <!-- 数据表格 -->
  <div>
    <NDataTable :loading="loading" :data="list" :columns="columns"></NDataTable>
    <div class="page">
      <NFlex justify="center">
        <NPagination
          v-model:page="page.pageNumber"
          :page-size="page.pageSize"
          :item-count="page.total"
          @update-page="query"
        ></NPagination>
      </NFlex>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { OptionInfo, TbLog } from '@/types/admin/System'
import { Api } from '@/types/Api'
import type { BaseDataResult, PageBean, PageVO } from '@/types/BaseResult'
import { onMounted, ref } from 'vue'
import {
  useMessage,
  NDataTable,
  NButton,
  NSelect,
  NSpace,
  NInput,
  type DataTableColumn,
  NPagination,
  NFlex,
} from 'naive-ui'
import { Tools } from '@/types/Tools'
const message = useMessage()

const page = ref({ pageSize: 10, pageNumber: 1 } as PageBean)
const queryInfo = ref({ logType: '', logInfo: '' })
const list = ref([] as Array<TbLog>)
const types = ref([] as Array<OptionInfo>)

const loading = ref(false)

const type = (t: string): string => {
  const v = types.value.find((info) => info.value == t)
  return v ? v.label : t
}

// 查询日志信息
const query = () => {
  loading.value = true
  Api.get(
    `/admin/log/${page.value.pageSize}/${page.value.pageNumber}`,
    queryInfo.value,
    (data: BaseDataResult<PageVO<TbLog>>) => {
      loading.value = false
      if (data.success) {
        list.value = data.data.list
        page.value = data.data.pageBean
        return
      }
      message.error(data.message)
    },
  )
}

const queryType = () => {
  loading.value = true
  Api.get('/admin/log/types', {}, (data: BaseDataResult<Array<OptionInfo>>) => {
    loading.value = false
    if (data.success) {
      types.value = [{ value: '', label: '请选择类型' }].concat(data.data)
      query()
      return
    }
    message.error(data.message)
  })
}

onMounted(() => {
  queryType()
})

const columns = [
  {
    title: '日志类型',
    key: 'logType',
    render: (row) => {
      return type(row.logType)
    },
  },
  { title: '日志内容', key: 'logInfo' },
  {
    title: '日期',
    key: 'lastupdate',
    render: (row) => {
      return Tools.formatDate(row.lastupdate)
    },
  },
] as DataTableColumn<TbLog>[]

const reset = () => {
  queryInfo.value = { logType: '', logInfo: '' }
  requery()
}
const requery = () => {
  page.value.pageNumber = 1
  query()
}
</script>

<style scoped lang="scss"></style>
